package cn.iot.sys.service.impl;


import cn.iot.common.utils.SysUserUtils;
import cn.iot.sys.dao.SysNoticeDao;
import cn.iot.sys.entity.SysNotice;
import cn.iot.sys.entity.SysUser;
import cn.iot.sys.entity.SysUserRole;
import cn.iot.sys.service.SysNoticeService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service("sysNoticeService")
public class SysNoticeServiceImpl extends ServiceImpl<SysNoticeDao, SysNotice> implements SysNoticeService {

    @Autowired
    private SysNoticeDao sysNoticeDao;



    @Override
    public SysNotice getOneSysNotice() {
        //获取当前用户
        SysUser userInfo = SysUserUtils.getSysUser();
        Long userId= userInfo.getId();
        List<SysUserRole> roleList = userInfo.getRoleInfoList();
        boolean isExists = roleList.stream().anyMatch(m->m.getRoleName().equals("市场部负责人"));

        SysNotice sysNotice = new SysNotice();
        LambdaQueryWrapper<SysNotice> wrapper = new LambdaQueryWrapper<>(sysNotice);
        wrapper.eq(SysNotice::getNoticeStatus,"0");
        wrapper.ne(SysNotice::getAlreadyQuery,"1");
        if(isExists){
            wrapper.eq(SysNotice::getIsRole,"1");
        }else{
            wrapper.eq(SysNotice::getIsRole,"0");
            wrapper.eq(SysNotice::getNoticeBy,userId);
        }
        wrapper.orderByDesc(SysNotice::getCreatedTime);



        List<SysNotice> list = sysNoticeDao.selectList(wrapper);
        if(list!=null&&list.size()>0){
            SysNotice snVO = list.get(0);
            snVO.setAlreadyQuery("1");
            sysNoticeDao.updateById(snVO);
            return snVO;
        }
        return null;
    }

    @Override
    public int updateNoticeStatus(SysNotice notice) {
        return sysNoticeDao.updateById(notice);
    }

    @Override
    public int addSysNotice(String title, String text, String receiveBy, boolean isRole) {
        SysNotice sysNotice = new SysNotice();
        sysNotice.setNoticeTitle(title);
        sysNotice.setNoticeContent(text);
        sysNotice.setNoticeBy(receiveBy);
        sysNotice.setNoticeStatus("0");
        sysNotice.setIsRole(isRole?"1":"0");
        sysNotice.setAlreadyQuery("0");
        return sysNoticeDao.insert(sysNotice);
    }
}
